import React, { useState } from 'react'
// 引入antd UI
import { Card, Form, Input, Button, Checkbox, message, Spin } from 'antd'
import { LoadingOutlined } from '@ant-design/icons'
// 引入logo图片
import logo from 'assets/logo.png'
// 引入样式
import styles from './index.module.scss'
// 引入接口
import { LoginUser } from 'api/login'
// 引入本地存储
import { setItem } from 'utils/stroage'

export default function Login(props) {
  // 自定义加载样式
  const antIcon = <LoadingOutlined style={{ fontSize: 24 }} spin />
  const [loading, setLoading] = useState(false)
  // 表单登录处理事件
  const login = async (val) => {
    //   请求数据前开启加载
    setLoading(true)
    const { mobile, code } = val
    try {
      // 点击登录发送请求
      const { data } = await LoginUser(mobile, code)
      setItem(data.data.token)
      //请求结束关闭加载
      setLoading(false)
      message.success('登录成功')
      //   登录成功进行跳转
      props.history.push('/home')
    } catch (err) {
      //请求结束关闭加载
      setLoading(false)
      message.error(err.response.data.message)
    }
  }
  return (
    <Spin indicator={antIcon} spinning={loading}>
      <div className={styles.login}>
        <Card className="login-container">
          {/* logo */}
          <img src={logo} alt="" className="login-logo" />
          {/* 登录表单 */}
          <Form
            name="basic"
            size="large"
            onFinish={login}
            initialValues={{
              mobile: '13911111111',
              code: '246810',
              agree: true,
            }}
          >
            <Form.Item
              name="mobile"
              validateTrigger={['onBlur']}
              rules={[
                {
                  required: true,
                  message: '请输入手机号!',
                },
                { pattern: /^1[3-9]\d{9}/, message: '手机号码格式不正确!' },
              ]}
            >
              <Input placeholder="请输入手机号" />
            </Form.Item>
            <Form.Item
              validateTrigger={['onBlur']}
              name="code"
              rules={[
                { required: true, message: '请输入验证码!' },
                { pattern: /\d{6}/, message: '验证码格式不对' },
              ]}
            >
              <Input.Password placeholder="请输入验证码" autoComplete="off" />
            </Form.Item>
            <Form.Item
              name="agree"
              valuePropName="checked"
              rules={[
                {
                  validator: (_, value) =>
                    value
                      ? Promise.resolve()
                      : Promise.reject(new Error('请阅读协议')),
                },
              ]}
            >
              <Checkbox>我已阅读并同意[用户协议]和[隐私条款]</Checkbox>
            </Form.Item>
            <Form.Item>
              <Button type="primary" htmlType="submit" block>
                登录
              </Button>
            </Form.Item>
          </Form>
        </Card>
      </div>
    </Spin>
  )
}
